package org.sample.algorithm.tree.trietree;

import org.apache.commons.lang3.StringUtils;

public class TrieTree {

    public void create(Node root, String str) {
        if (StringUtils.isBlank(str))
            return;

        char[] chs = str.toCharArray();
        for (char ch : chs) {
            int pos = ch - 'a';
            if (root.childs[pos] == null)
                root.childs[pos] = new Node(ch);
            else
                root.childs[pos].count++;
            root = root.childs[pos];
        }
    }

    public int findCount(Node root, String str) {
        if (StringUtils.isBlank(str))
            return -1;

        char[] chs = str.toCharArray();
        for (char ch : chs) {
            int pos = ch - 'a';
            if (root.childs[pos] == null)
                return 0;
            else
                root = root.childs[pos];
        }
        return root.count;
    }

    public static void trieTreeTest2() {
        String[] strs = {"banana", "band", "bee", "absolute", "acm",};
        String[] prefix = {"ba", "b", "band", "abc",};
        TrieTree tree = new TrieTree();
        Node root = new Node();

        for (String s : strs) {
            tree.create(root, s);
        }
// tree.printAllWords();
        for (String pre : prefix) {
            int num = tree.findCount(root, pre);
            System.out.println(pre + " " + num);
        }

    }

    public static void main(String[] args) {
        trieTreeTest2();
    }

}
